package org.jeecg.modules.hc.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.SignatureHeader;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyV3Result;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.http.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.hc.entity.HcWxPay;
import org.jeecg.modules.hc.service.IHcOrderService;
import org.jeecg.modules.hc.service.IHcWxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Arrays;

import static com.wechat.pay.java.core.http.UrlEncoder.urlEncode;

/**
 * @Description: 微信支付
 * @Author: jeecg-boot
 * @Date: 2023-01-07
 * @Version: V1.0
 */
@Api(tags = "微信支付")
@RestController
@RequestMapping("/hc/hcWxPay")
@Slf4j
public class HcWxPayController extends JeecgController<HcWxPay, IHcWxPayService> {
    @Autowired
    private IHcWxPayService hcWxPayService;

    @Autowired
    private WxPayService payService;

    @Autowired
    private IHcOrderService hcOrderService;

    @ApiOperation("/test")
    @RequestMapping("/test")
    public Result<?> test() throws WxPayException {
        HcWxPay pay = hcWxPayService.pay("jsapi", "1", "oXtJg6YU-Ak7uHhxnzuJxVKx5PHo", "用膳团", new BigDecimal("0.01"));
        return Result.ok(pay);
    }

    /**
     * 由微信支付平台的服务调用 此接口，将微信支付结果推送给 点餐系统后端服务；
     * @param request
     * @return
     * @throws WxPayException
     */
    @ApiOperation("/回调")
    @RequestMapping("/notify")
    public Result<?> notifyHandle(HttpServletRequest request) throws WxPayException {
        String requestBody = getRequestBody(request);
        log.info("回调参数：{}", requestBody);
        SignatureHeader signatureHeader = new SignatureHeader();
        signatureHeader.setNonce(request.getHeader("Wechatpay-Nonce"));
        signatureHeader.setTimeStamp(request.getHeader("Wechatpay-Timestamp"));
        signatureHeader.setSignature(request.getHeader("Wechatpay-Signature"));
        signatureHeader.setSerial(request.getHeader("Wechatpay-Serial"));
        log.info("回调 header：{}", JSON.toJSONString(signatureHeader));
        WxPayOrderNotifyV3Result wxPayOrderNotifyV3Result = payService.parseOrderNotifyV3Result(requestBody, signatureHeader);
        log.info("回调 wxPayOrderNotifyV3Result：{}", JSON.toJSONString(wxPayOrderNotifyV3Result.getResult()));
        hcOrderService.notifyOrder(wxPayOrderNotifyV3Result);
        return Result.ok();
    }
    /**
     * 读取请求数据流
     *
     * @param request
     * @return
     */
    private String getRequestBody(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();

        try (ServletInputStream inputStream = request.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            String line;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            log.error("读取数据流异常:{}", e);
        }

        return sb.toString();
    }

    /**
     * 分页列表查询
     *
     * @param hcWxPay
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "微信支付-分页列表查询")
    @ApiOperation(value = "微信支付-分页列表查询", notes = "微信支付-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<HcWxPay>> queryPageList(HcWxPay hcWxPay,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        QueryWrapper<HcWxPay> queryWrapper = QueryGenerator.initQueryWrapper(hcWxPay, req.getParameterMap());
        Page<HcWxPay> page = new Page<HcWxPay>(pageNo, pageSize);
        IPage<HcWxPay> pageList = hcWxPayService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hcWxPay
     * @return
     */
    @AutoLog(value = "微信支付-添加")
    @ApiOperation(value = "微信支付-添加", notes = "微信支付-添加")
    //@RequiresPermissions("org.jeecg.modules:hc_wx_pay:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody HcWxPay hcWxPay) {
        hcWxPayService.save(hcWxPay);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hcWxPay
     * @return
     */
    @AutoLog(value = "微信支付-编辑")
    @ApiOperation(value = "微信支付-编辑", notes = "微信支付-编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_wx_pay:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody HcWxPay hcWxPay) {
        hcWxPayService.updateById(hcWxPay);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "微信支付-通过id删除")
    @ApiOperation(value = "微信支付-通过id删除", notes = "微信支付-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:hc_wx_pay:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hcWxPayService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "微信支付-批量删除")
    @ApiOperation(value = "微信支付-批量删除", notes = "微信支付-批量删除")
    //@RequiresPermissions("org.jeecg.modules:hc_wx_pay:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hcWxPayService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "微信支付-通过id查询")
    @ApiOperation(value = "微信支付-通过id查询", notes = "微信支付-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<HcWxPay> queryById(@RequestParam(name = "id", required = true) String id) {
        HcWxPay hcWxPay = hcWxPayService.getById(id);
        if (hcWxPay == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hcWxPay);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hcWxPay
     */
    //@RequiresPermissions("org.jeecg.modules:hc_wx_pay:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcWxPay hcWxPay) {
        return super.exportXls(request, hcWxPay, HcWxPay.class, "微信支付");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("hc_wx_pay:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcWxPay.class);
    }

}
